import { mkdirSync, readFileSync, readdirSync, writeFileSync } from "fs";
import Utils from "./Utils";
import path = require("path");
import { readFile, readdir } from "fs/promises";

export default class LocalStore {
    private static _store: {[key: string]: string} = {};

    public static init(): Promise<any> {
        return new Promise((resolve: (v?: any)=>void, reject) => {
            readdir(path.join(Utils.root, "./store"))
            .then((flist) => {
                if (flist.indexOf("store.json") >= 0) {
                    let _data = readFileSync(path.join(Utils.root, './store/store.json'));
                    this._store = JSON.parse(_data.toString());
                    resolve();
                }
                else {
                    writeFileSync(path.join(Utils.root, './store/store.json'), "{}");
                    this._store = {};
                    resolve();
                }
            })
            .catch((err) => {
                mkdirSync(path.join(Utils.root, "./store"));
                writeFileSync(path.join(Utils.root, './store/store.json'), "{}");
                this._store = {};
                resolve();
            });
        });
    }

    public static get(key: string): string | null {
        return this._store[key] || null;
    }

    public static set(key: string, value: string) {
        this._store[key] = value;
        writeFileSync(path.join(Utils.root, './store/store.json'), JSON.stringify(this._store));
    }

    public static getAll() {
        return this._store;
    }

    public static setAll(data: {[key: string]: string}) {
        this._store = {...data};
        writeFileSync(path.join(Utils.root, './store/store.json'), JSON.stringify(this._store));
    }
}